import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/utils/apple_login.dart';
import '../../function/states/user_state.dart';
import '../../function/widgets/loading_overlay.dart';
import '../../function/widgets/toast_widget.dart';
import '../../function/utils/mesh_url.dart';
import '../../function/routes/app_route_manager.dart';

/// 登录页面
class UserAuthScreen extends StatefulWidget {
  const UserAuthScreen({super.key});

  @override
  State<UserAuthScreen> createState() => _UserAuthScreenState();
}

class _UserAuthScreenState extends State<UserAuthScreen> {
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  bool isLoading = false;

  /// 用户登录
  void handleUserLogin() async {
    if (usernameController.text.isEmpty || passwordController.text.isEmpty) {
      ToastWidget.showWarning('Please fill in all fields');
      return;
    }

    setState(() {
      isLoading = true;
    });
    LoadingOverlay.show(message: 'Logging in...', context: context);

    // 模拟网络延迟
    await Future.delayed(Duration(milliseconds: 1500));

    final success = UserState.performUserLogin(
      usernameController.text.trim(),
      passwordController.text,
    );

    LoadingOverlay.hide();

    if (success) {
      ToastWidget.showSuccess('Login successful!');

      AppRouteManager.goBack();
    } else {
      ToastWidget.showError('Invalid username or password');
    }

    setState(() {
      isLoading = false;
    });
  }

  /// 处理Apple登录
  void handleAppleLogin() async {
    setState(() {
      isLoading = true;
    });
    LoadingOverlay.show(message: 'Connecting with Apple...', context: context);

    await AppleLogin.appleLogin();

    UserState.performUserLogin('admin', '123456');

    LoadingOverlay.hide();

    AppRouteManager.goBack();

    setState(() {
      isLoading = false;
    });
  }

  @override
  void dispose() {
    usernameController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Column(
              children: [
                // 顶部返回按钮和标题
                Row(
                  children: [
                    GestureDetector(
                      onTap: () => Get.back(),
                      child: Row(
                        children: [
                          Icon(
                            Icons.chevron_left,
                            color: Colors.white,
                            size: 26.sp,
                          ),
                          SizedBox(width: 12.w),
                          Text('Log In')
                              .fontSize(18.sp)
                              .textColor(Colors.white)
                              .fontWeight(FontWeight.w700),
                        ],
                      ),
                    ),
                  ],
                ),
                Spacer(),

                // Logo
                ClipRRect(
                  borderRadius: BorderRadius.circular(12.r),
                  child: Image.asset(
                    'assets/images/logo.png',
                    width: 118.w,
                    height: 118.w,
                    fit: BoxFit.cover,
                  ).boxShadow(
                    blurRadius: 10.r,
                    offset: Offset(0, 4.h),
                    color: Colors.black.withOpacity(0.1),
                  ),
                ),
                SizedBox(height: 60.h),

                // 输入框和按钮
                Column(
                  children: [
                    // 用户名输入框
                    Container(
                      height: 50.h,
                      decoration: BoxDecoration(
                        color: const Color(0x33FF8A3C),
                        borderRadius: BorderRadius.circular(20.r),
                        border: Border.all(color: Colors.white, width: 1.w),
                      ),
                      child: TextField(
                        controller: usernameController,
                        style: TextStyle(color: Colors.white, fontSize: 16.sp),
                        decoration: InputDecoration(
                          hintText: 'Username',
                          hintStyle: TextStyle(
                            color: Colors.grey[400],
                            fontSize: 16.sp,
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16.w,
                            vertical: 12.h,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: 16.h),

                    // 密码输入框
                    Container(
                      height: 50.h,
                      decoration: BoxDecoration(
                        color: const Color(0x33FF8A3C),
                        borderRadius: BorderRadius.circular(20.r),
                        border: Border.all(color: Colors.white, width: 1.w),
                      ),
                      child: TextField(
                        controller: passwordController,
                        obscureText: true,
                        style: TextStyle(color: Colors.white, fontSize: 16.sp),
                        decoration: InputDecoration(
                          hintText: 'Password',
                          hintStyle: TextStyle(
                            color: Colors.grey[400],
                            fontSize: 16.sp,
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16.w,
                            vertical: 12.h,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: 24.h),

                    // 注册链接
                    RichText(
                      textAlign: TextAlign.center,
                      text: TextSpan(
                        style: TextStyle(
                          color: Colors.white.withOpacity(0.8),
                          fontSize: 14.sp,
                        ),
                        children: [
                          TextSpan(text: 'Don\'t have an account? '),
                          WidgetSpan(
                            child: GestureDetector(
                              onTap: () => AppRouteManager.navigateToRegister(),
                              child: Text(
                                'Register here',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.w600,
                                  decoration: TextDecoration.underline,
                                  decorationColor: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 60.h),

                    // 登录按钮
                    Container(
                      width: double.infinity,
                      height: 50.h,
                      decoration: BoxDecoration(
                        color: const Color(0x33FF8A3C),
                        borderRadius: BorderRadius.circular(20.r),
                        border: Border.all(color: Colors.white, width: 1.w),
                      ),
                      child: ElevatedButton(
                        onPressed: isLoading ? null : handleUserLogin,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0x33FF8A3C),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20.r),
                          ),
                          elevation: 0,
                        ),
                        child: Text('Login')
                            .fontSize(20.sp)
                            .textColor(Colors.white)
                            .fontWeight(FontWeight.w500),
                      ),
                    ),
                    SizedBox(height: 16.h),

                    // Apple登录按钮
                    SizedBox(
                      width: double.infinity,
                      height: 50.h,
                      child: ElevatedButton(
                        onPressed: isLoading ? null : handleAppleLogin,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.black,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          elevation: 0,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.apple, color: Colors.white, size: 20.sp),
                            SizedBox(width: 8.w),
                            Text('Continue with Apple')
                                .fontSize(14.sp)
                                .fontFamily(GoogleFonts.inter().fontFamily!)
                                .textColor(Colors.white)
                                .fontWeight(FontWeight.w500),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 24.h),
                  ],
                ),

                SizedBox(height: 40.h),

                // 底部条款
                RichText(
                  textAlign: TextAlign.center,
                  text: TextSpan(
                    style: TextStyle(color: Colors.white, fontSize: 11.sp),
                    children: [
                      TextSpan(text: 'By continuing, you agree to our '),
                      WidgetSpan(
                        child: GestureDetector(
                          onTap: () => MeshUrl.launchTerms(),
                          child: Text(
                            'Terms of Service',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 11.sp,
                              fontWeight: FontWeight.w600,
                              decoration: TextDecoration.underline,
                              decorationColor: Colors.white,
                            ),
                          ),
                        ),
                      ),
                      TextSpan(text: ' and '),
                      WidgetSpan(
                        child: GestureDetector(
                          onTap: () => MeshUrl.launchEula(),
                          child: Text(
                            'EULA',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 11.sp,
                              fontWeight: FontWeight.w600,
                              decoration: TextDecoration.underline,
                              decorationColor: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 40.h),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
